package com.mzba.place.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.ui.widget.DateSlider;
import com.mzba.place.ui.widget.DateTimeSlider;
import com.mzba.place.ui.widget.TimeLabeler;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageThumbnail;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;

/**
 * @author iris
 * 
 */
public class ReportUploadActivity extends BasicActivity implements Callback, BasicUIEvent, OnClickListener {

	private RelativeLayout rl_address, rl_photo, rl_time;
	private EditText et_content;

	private TextView tv_address, tv_time;
	
	private ImageView iv_photo;
	private ImageView iv_buleline;
	private Spinner reportTypeSpinner;
	private final int request_map = 200;
	private File picFile;
	private final static int REQUEST_WIDTH = 1000;

	private final int activity_result_camara_with_data = 202;
	private final int activity_result_pick_with_data = 203;
	/**
	 * 上报
	 */
	private final int menu_upload = 0x1235;
	private final int menu_upload_error = 0x1236;
	private Handler handler;
	private ArrayAdapter<CharSequence> reportTypeAdapter;
	/**
	 * 地图界面的lon
	 */
	private double lon;
	private double lat;
	private String address;
	/**
	 * 默认的lon
	 */
	private double localLon;
	private double localLat;
	PlaceApplication app;
	public MKSearch mSearch = null;
	
	private WeakReference<Bitmap> photoBitmap;
	static final int DATETIMESELECTOR_ID = 1;
	
	private String time;
	WeakReference<Bitmap> avatarBitmap;
	private ImageView iv_user_icon;
	private TextView tv_user_name;
	RegisterEntity entry;
	private Context context;
	private int type;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_report_upload);
		setSupportProgressBarIndeterminateVisibility(false);
		context = this;
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle("添加上报信息");
		app = (PlaceApplication) getApplication();
		
		
		init();
		setTitle("Report");
		handler = new Handler(this);
		initAddress();
	}

	private void init() {
		rl_address = (RelativeLayout) findViewById(R.id.rl_address);
		rl_photo = (RelativeLayout) findViewById(R.id.add_photo_layout);
		rl_time = (RelativeLayout) findViewById(R.id.rl_time);
		rl_time.setOnClickListener(this);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_time.setText(Utils.getCurrentTime());
		reportTypeSpinner = (Spinner) findViewById(R.id.report_type_spinner);
		reportTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				type = arg2;
				TextView tv = (TextView) arg1;
				tv.setTextColor(Color.BLACK);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		iv_user_icon = (ImageView)findViewById(R.id.iv_user_icon);
		tv_user_name = (TextView)findViewById(R.id.iv_user_name);
		et_content = (EditText) findViewById(R.id.et_content);
		tv_address = (TextView) findViewById(R.id.tv_address);
		iv_photo = (ImageView) findViewById(R.id.iv_photo);
		iv_photo.setOnClickListener(this);
		iv_buleline = (ImageView) findViewById(R.id.blue_line);
		rl_address.setOnClickListener(this);
		rl_photo.setOnClickListener(this);
		rl_photo.setOnClickListener(this);
		reportTypeAdapter = ArrayAdapter.createFromResource(this,R.array.reportType_4, R.layout.spinner_item);
		reportTypeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		reportTypeSpinner.setAdapter(reportTypeAdapter);
		setUserinfoView();
	}
	
	private void initAddress(){
		localLon = app.longitude;
		localLat = app.latitude;
		mSearch = new MKSearch();
		initMKSearch();
		GeoPoint pt = new GeoPoint((int)(localLat * 1E6), (int)(localLon* 1E6));
		mSearch.reverseGeocode(pt);
	}
	
	private void setUserinfoView() {
		try {
			UserTable ut = new UserTable(this);
			 entry = ut.get();
			if (StringUtil.isNotBlank(entry.getUsername())) {
				tv_user_name.setText(entry.getUsername());
			}
			if (StringUtil.isNotBlank(entry.getAvatar_url())) {
				new Thread() {
					public void run() {
						 avatarBitmap = new WeakReference<Bitmap>(Utils.getBitmap(context, entry.getAvatar_url()));
						 ((Activity) context).runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								if (avatarBitmap.get() != null) {
									iv_user_icon.setImageBitmap(Utils.toRoundBitmap(avatarBitmap.get()));
								}
							}
						});
					};
				}.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.add_photo_layout:
			doPickPhotoAction();
			break;
		case R.id.rl_address:
			intent = new Intent(ReportUploadActivity.this, MapMyLocalActivity.class);
			startActivityForResult(intent, request_map);
			break;
		case R.id.rl_time:
			showDialog(DATETIMESELECTOR_ID);
			break;
		case R.id.iv_photo:
			showChoseMes("确定要删除该照片吗？", 0);
			break;
		default:
			break;
		}

	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == 0) {
			iv_photo.setImageBitmap(null);
			picFile = null;
			iv_buleline.setVisibility(View.GONE);
			iv_photo.setVisibility(View.GONE);
			if (photoBitmap != null && photoBitmap.get() != null && !photoBitmap.get().isRecycled()) {
				photoBitmap.get().recycle();
				photoBitmap = null;
			}
			System.gc();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.mzba.place.BasicActivity#execute(int, java.lang.Object)
	 */
	@Override
	public void execute(int mes, Object obj) {
		try {
			HashMap<String, String> map;
			switch (mes) {
			case menu_upload:
				map = new HashMap<String, String>();

				map.put("auth_token", AppContext.getInstance().getAuthToken());
				map.put("content", et_content.getText().toString().trim());
				if (lon != 0.0 || lat != 0.0) {
					map.put("longitude", String.valueOf(lon));
					map.put("latitude", String.valueOf(lat));
				} else {
					map.put("longitude",String.valueOf(localLon));
					map.put("latitude",String.valueOf(localLat));
				}
				map.put("r_type", String.valueOf(type + 1));
				map.put("from", "android_app");
				if (StringUtil.isNotBlank(time)) {
					map.put("r_time", time);
				}
				String response = null;
				if (picFile != null) {
					response = HttpUtils.post(UrlConfig.reports, map, picFile);
				} else {
					response = HttpUtils.doPost(this, UrlConfig.reports, map);
				}
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					ReportEntity entry = gson.fromJson(response, ReportEntity.class);
					if (entry != null) {
						handler.sendEmptyMessage(menu_upload);
					} else {
						handler.sendEmptyMessage(menu_upload_error);
					}
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.execute(mes, obj);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.actionbarsherlock.app.SherlockFragmentActivity#onCreateOptionsMenu
	 * (com.actionbarsherlock.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (menu != null) {
			menu.clear();
			menu.add(0, menu_upload, 0, "上报").setIcon(R.drawable.abs__ic_cab_done_holo_dark)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
		return true;
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case menu_upload:
			Toast.makeText(this, "操作成功", Toast.LENGTH_LONG).show();
			setResult(RESULT_OK);
			finish();
			break;
		case menu_upload_error:
			Toast.makeText(this, "操作失败", Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case menu_upload:
//			int type = reportTypeSpinner.getSelectedItemPosition();
//			if (type == 0) {
//				Toast.makeText(this, "请选择上报类型！", Toast.LENGTH_LONG).show();
//				return false;
//			}
			if (StringUtil.isBlank(et_content.getText().toString().trim())) {
				Toast.makeText(this, "请填写事件描述！", Toast.LENGTH_LONG).show();
				return false;
			}
			UICore.eventTask(ReportUploadActivity.this, this, menu_upload, null, true);
			break;
		default:
			break;
		}
		return false;
	}

	/**
	 * 选择拍照方式
	 */
	private void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String cancel = getString(R.string.confirm_back);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.expand_edit_take_photo); // 拍照
		choices[1] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String status = Environment.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							break;
						case 1:
							doSelectImageFromLoacal();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File pictureFileDir = new File(AppContext.getSDPath(), "temp");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			Uri pictureUri = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
			startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从本地手机中选择图片
	 */
	private void doSelectImageFromLoacal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = Intent.createChooser(localIntent, "选择照片");
		startActivityForResult(localIntent2, activity_result_pick_with_data);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == request_map) {
				if (data != null) {
					int latitude = data.getIntExtra("latitude", 0);
					int longitude = data.getIntExtra("longitude", 0);
					lat = latitude / 1E6;
					lon = longitude / 1E6;
					address = data.getStringExtra("address");
					tv_address.setText(address);
				}
			} else if (requestCode == activity_result_camara_with_data) {
				try {
					File pictureFileDir = new File(AppContext.getSDPath(), "temp");
					picFile = new File(pictureFileDir, "upload.jpeg");
					if (picFile != null && picFile.length() > 0) {
						InputStream inputStream1 = new FileInputStream(picFile);
						InputStream inputStream2 = new FileInputStream(picFile);
						Bitmap bitmapDecode = ImageThumbnail.decodeStream(
								inputStream1, inputStream2, REQUEST_WIDTH);
						if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
							photoBitmap = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
						} else {
							photoBitmap = new WeakReference<Bitmap>(bitmapDecode);
						}
						int width = photoBitmap.get().getWidth();
						int height = photoBitmap.get().getHeight();
						Matrix matrix = new Matrix();
						int degree = ImageThumbnail.getExifOrientation(picFile.getAbsolutePath());
						matrix.setRotate(degree);
						System.out.println("------------------------->>>" + degree);
						photoBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(photoBitmap.get(), 0, 0, width, height, matrix, true));
						pictureFileDir = new File(AppContext.getSDPath(), "upload");
						if (!pictureFileDir.isDirectory()) {
							pictureFileDir.mkdirs();
						}
						picFile = new File(pictureFileDir, "upload.jpeg");
						FileOutputStream ous = new FileOutputStream(picFile);
						photoBitmap.get().compress(Bitmap.CompressFormat.JPEG, 100, ous);
						photoBitmap = new WeakReference<Bitmap>(ThumbnailUtils.extractThumbnail(photoBitmap.get(), CanvasWidth, 200));
						iv_photo.setImageBitmap(photoBitmap.get());
						iv_photo.setVisibility(View.VISIBLE);
						iv_buleline.setVisibility(View.VISIBLE);
						ous.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (requestCode == activity_result_pick_with_data) {
				if (data == null) {
					return;
				}
				Uri uri = data.getData();
				ContentResolver resolver = getContentResolver();
				try {
					InputStream inputStream1 = resolver.openInputStream(uri);
					InputStream inputStream2 = resolver.openInputStream(uri);
					Bitmap bitmapDecode = ImageThumbnail.decodeStream(inputStream1, inputStream2, REQUEST_WIDTH);
					if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
						photoBitmap = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
					} else {
						photoBitmap = new WeakReference<Bitmap>(bitmapDecode);
					}
					File pictureFileDir = new File(AppContext.getSDPath(), "temp");
					if (!pictureFileDir.exists()) {
						pictureFileDir.mkdirs();
					}
					picFile = new File(pictureFileDir, "upload.jpeg");
					if (!picFile.exists()) {
						picFile.createNewFile();
					}
					FileOutputStream ous = new FileOutputStream(picFile);
					photoBitmap.get().compress(Bitmap.CompressFormat.PNG, 100, ous);
					int width = photoBitmap.get().getWidth();
					int height = photoBitmap.get().getHeight();
					Matrix matrix = new Matrix();
					int degree = ImageThumbnail.getExifOrientation(picFile.getAbsolutePath());
					matrix.setRotate(degree);
					System.out.println("------------------------->>>" + degree);
					photoBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(photoBitmap.get(), 0, 0, width, height, matrix, true));
					photoBitmap = new WeakReference<Bitmap>(ThumbnailUtils.extractThumbnail(photoBitmap.get(), CanvasWidth, 200));
					iv_photo.setImageBitmap(photoBitmap.get());
					iv_photo.setVisibility(View.VISIBLE);
					iv_buleline.setVisibility(View.VISIBLE);
					ous.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void onDestroy() {
		super.onDestroy();
		try {
			File uploadFileDir = new File(AppContext.getSDPath(), "upload");
			File file = new File(uploadFileDir, "upload.jpeg");
			if (file.exists()) {
				file.delete();
			}
			if (photoBitmap != null && photoBitmap.get() != null && !photoBitmap.get().isRecycled()) {
				photoBitmap.get().recycle();
				photoBitmap = null;
			}
			if (picFile != null) {
				picFile.delete();
				picFile = null;
			}
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
	};
	
	private void initMKSearch() {
		mSearch.init(app.mBMapManager, new MKSearchListener() {
			
			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { }
			
			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { }
			
			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int error) { }
			
			@Override
			public void onGetPoiResult(MKPoiResult arg0, int res, int error) { }
			
			@Override
			public void onGetPoiDetailSearchResult(int res, int error) { }
			
			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { }
			
			@Override
			public void onGetBusDetailResult(MKBusLineResult res, int error) { }
			
			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) { 
				destroyDialog();
				try {
					if (error != 0) {
						return;
					}
					if (res.geoPt != null) {
						localLat = res.geoPt.getLatitudeE6() / 1E6;
						localLon = res.geoPt.getLongitudeE6() / 1E6;
						address = res.strAddr;
						tv_address.setText(address);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
	}
	
	private DateSlider.OnDateSetListener mDateTimeSetListener =
	        new DateSlider.OnDateSetListener() {
	            public void onDateSet(DateSlider view, Calendar selectedDate) {
	                // update the dateText view with the corresponding date
	                int minute = selectedDate.get(Calendar.MINUTE) /
	                        TimeLabeler.MINUTEINTERVAL*TimeLabeler.MINUTEINTERVAL;
	                time = String.format("%tY-%tm-%te %tH:%02d", selectedDate, selectedDate, selectedDate, selectedDate, minute);
	                tv_time.setText(time);
	                
	            }
	    };
	    
	    @Override
	    protected Dialog onCreateDialog(int id) {
	    	final Calendar c = Calendar.getInstance();
	    	return new DateTimeSlider(this, mDateTimeSetListener, c);
	    }

}
